package me.zhengjie.modules.security.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.io.UnsupportedEncodingException;

/**
 * 微信登录配置
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "wx")
public class WxConfig {
    
    /**
     * 微信AppID
     */
    private String appId;
    
    /**
     * 微信AppSecret
     */
    private String appSecret;
    
    /**
     * 微信登录回调地址
     */
    private String redirectUrl;
    
    /**
     * 获取微信授权码的URL (网页授权)
     */
    public String getAuthCodeUrl(String state) {
        try {
            String encodedRedirectUrl = URLEncoder.encode(redirectUrl, "UTF-8");
            return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId +
                    "&redirect_uri=" + encodedRedirectUrl +
                    "&response_type=code&scope=snsapi_userinfo&state=" + state + "#wechat_redirect";
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("URL编码失败", e);
        }
    }
    
    /**
     * 获取微信访问令牌的URL (网页授权)
     */
    public String getAccessTokenUrl(String code) {
        return "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId +
                "&secret=" + appSecret +
                "&code=" + code +
                "&grant_type=authorization_code";
    }
    
    /**
     * 获取微信小程序会话信息的URL
     */
    public String getJscode2SessionUrl(String code) {
        return "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId +
                "&secret=" + appSecret +
                "&js_code=" + code +
                "&grant_type=authorization_code";
    }
    
    /**
     * 获取微信用户信息的URL (网页授权)
     */
    public String getUserInfoUrl(String accessToken, String openId) {
        return "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken +
                "&openid=" + openId +
                "&lang=zh_CN";
    }
} 